package com.yzi.core.thread
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class Looper implements IRunnable
	{
		static public var MilliSecond:uint = 1;
		
		private var m_executor:Timer;
		private var m_runnable:IRunnable;
		private var m_count:uint;
		
		public function Looper()
		{
			init();
		}
		
		private function init(): void
		{
			m_executor = new Timer(Looper.MilliSecond);
			
			m_count = 0;
		}
		
		private function onLoop($event:TimerEvent): void
		{
			Loop();
			m_count++;
		}
		
		public function Run():void
		{
			
		}
		
		final public function Loop($runnable:IRunnable=null): void
		{
			if(m_executor.delay != MilliSecond) m_executor.delay = MilliSecond;
			if(!m_runnable) m_runnable = $runnable;
			if(!m_executor.running) m_executor.start();
			if(!m_runnable) m_runnable = this; 
			m_runnable.Run();
		}
		
		final public function Reset(): void  { m_count = 0; }
		
		final public function Stop(): void
		{
			m_executor.stop();
		}
		
		final public function Destory(): void
		{
			m_executor.removeEventListener(TimerEvent.TIMER, onLoop);
			m_executor = null;
		}
		
		final public function GetCount(): uint  { return m_count; }
	}
}